package models.accesscard;

import models.UUIDModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import util.common.ConvertUtil;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

/**
 * 门禁卡.
 */
@Entity
@Table(name = "as_cards")
public class AccessCard extends UUIDModel {

    public AccessCard() {
    }

    public AccessCard(String code, String serial) {
        this.code = code;
        this.serial = serial;
    }

    /**
     * 门禁卡卡号, 随机编码.
     */
    @Column(name = "code", length = 20)
    public String code;

    /**
     * 序列号，有顺序的编号.
     */
    @Column(name = "serial", length = 30)
    public String serial;

    /**
     * 批量插入门禁卡信息
     *
     * @param accessCardList
     */
    public static void insertAccessCardList(List<Map<String, Object>> accessCardList , AdminUser loginUser) {
        for (Map<String, Object> importData : accessCardList) {
            String code = ConvertUtil.toString(importData.get("code"));
            String serial = ConvertUtil.toString(importData.get("serial"));

            if (!code.isEmpty() && !serial.isEmpty()) {
                long isExists = AccessCard.count("code=? or serial=?", code, serial);
                if (isExists == 0) {
                    AccessCard accessCard = new AccessCard(code, serial);
                    accessCard.createdAt = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
                    accessCard.deleted = DeletedStatus.UN_DELETED;
                    accessCard.createUser = loginUser ;
                    accessCard.belongCompany = loginUser.organization != null ? loginUser.organization : null ;
                    accessCard.save();
                }
            }
        }
    }


    /**
     * 根据 code 查找卡号信息
     *
     * @param code
     * @return
     */
    public static AccessCard findByCardNumber(String code) {
        return AccessCard.find("code = ?1 and deleted = ?2", code, DeletedStatus.UN_DELETED).first();
    }

}
